/**
 * Electron 主进程入口。
 * 创建窗口并处理主进程与渲染进程的通信。
 */

import {app, BrowserWindow, ipcMain, dialog, shell} from 'electron';
import path from 'path';
import * as fs from "node:fs";

function createWindow() {

    const win = new BrowserWindow({
        width: 1042,
        height: 720,
        webPreferences: {
            contextIsolation: true, // 启用上下文隔离
            nodeIntegration: false, // 禁用 Node.js 集成
            devTools: true, // 确保允许调试器
            preload: path.join(app.getAppPath(), 'dist', 'electron', 'preload.js')
        },
    });

    if (process.env.VITE_DEV_SERVER_URL) {
        win.loadURL(process.env.VITE_DEV_SERVER_URL).then();
        setTimeout(() => {
            win.webContents.openDevTools();
        }, 1000);
    } else {
        win.loadFile(path.join(app.getAppPath(), 'dist', 'react', 'index.html')).then();
    }
}

app.whenReady().then(createWindow);
app.on('window-all-closed', () => app.quit());

// IPC 示例
ipcMain.handle('ping', () => 'pong from main');

ipcMain.handle('open-pdf-dialog', (_, extensions = []) => {
    return new Promise((resolve, reject) => {
        dialog.showOpenDialog({
            title: '选择 PDF 或 Word 文件',
            properties: ['openFile'],
            filters: [
                {name: '文档文件', extensions: extensions} // 'pdf', 'doc', 'docx'
            ]
        }).then(async (result) => {
            if (!result.canceled) {
                const filePath = result.filePaths[0];
                fs.readFile(filePath, (err, data) => {
                    if (err || !data) {
                        reject(err);
                    } else {
                        resolve({
                            filePath: filePath,
                            fileName: path.basename(filePath),
                            arrayBuffer: data.buffer // 转为 ArrayBuffer 以便跨进程传输
                        });
                    }
                })
            }
        })
    })
});

ipcMain.handle('open-directory-dialog', async () => {
    const result = await dialog.showOpenDialog({
        title: '选择保存目录',
        properties: ['openDirectory', 'createDirectory'],
    });
    return result.canceled ? null : result.filePaths[0];
});

ipcMain.handle('save-image', async (_, dirPath, images) => {

    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-expect-error
    const saveImage = async (fileName, data) => {
        try {
            const filePath = path.join(dirPath, fileName);
            // await fs.writeFile(filePath, Buffer.from(data, 'base64')); // 假设 data 是 base64
            fs.writeFile(filePath, Buffer.from(data, 'base64'), (err) => {
                if (!err) {
                    console.log(`${fileName} created`);
                } else {
                    console.error(`Error creating ${fileName}:`, err);
                }
            }); // 直接写入二进制buffer
        } catch (error) {
            console.error(error);
        }
    }

    try {
        // 检查目录是否存在，不存在则创建 const dirExists = await fs.promises.access(dirPath)
        if (!fs.existsSync(dirPath)) {
            fs.mkdirSync(dirPath, {recursive: true});
        }

        // 批量保存图片
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-expect-error
        images.map(async ({fileName, buffer}) => {
            await saveImage(fileName, buffer);
        })

        return {success: true, results: []};
    } catch (error) {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-expect-error
        return {success: false, error: error.message};
    }
});

ipcMain.handle('open-save-path', async (_, path) => {
    await shell.openPath(path);
});

ipcMain.handle('show-directory', async () => {
    // eslint-disable-next-line no-useless-catch
    try {
        const result = [];
        const appPath = app.getAppPath(); // 获取应用根目录路径
        result.push({type: '[file]', path: `appPath: ${appPath}`});
        // 列出根目录的所有文件和目录
        const files = await fs.promises.readdir(appPath, {withFileTypes: true});
        files.forEach(file => {
            if (file.isDirectory()) {
                result.push({type: '[Directory]', path: file.name});
            } else {
                result.push({type: '[File]', path: file.name});
            }
        });
        return result;
    } catch (err) {
        throw err;
    }
});